The if...else statement is used to execute a block of code based on a specified condition. If the
condition is true, the block of code inside the if statement is executed. Otherwise, the block of
code inside the else statement is executed.
Here is an example of a basic if...else statement:
let isRaining = true;
if (isRaining) {
console.log("Take an umbrella!");
} else {
console.log("No need for an umbrella.");
}
The else if statement is used to specify multiple conditions:
let temperature = 30;
if (temperature > 30) {
console.log("It's hot outside!");
} else if (temperature < 15) {
console.log("It's cold outside!");
} else {
console.log("The weather is moderate.");
}
You can also nest if...else statements within each other:
let age = 20;
let hasPermission = true;
if (age >= 18) {
if (hasPermission) {
console.log("You can enter the club.");
} else {
console.log("You need permission to enter the club.");
}
} else {
console.log("You are too young to enter the club.");
}
The ternary operator is a shorthand for the if...else statement:
let isMember = true;
let discount = isMember ? 10 : 0;
console.log(`You get a ${discount}% discount.`); // Outputs: You get a 10% discount.